<?php

namespace App\Console\Commands;

use App\Func\AppFunc;
use App\Func\CurlFunc;
use App\Func\MeLawCaseFunc;
use App\Models\MeClient\MeClientModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeLawCase\MeLawCasePhoneModel;
use Illuminate\Console\Command;

class ImportCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:importExcelMe';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
//        $url = "https://47.108.159.96:39351/setProceedMap";
        $url = AppFunc::getSystemConfig()::HTTP_BASE_URL.":39351/setProceedMap";
//        $url = AppFunc::getSystemConfig()::HTTPS_BASE_URL.":39351/setProceedMap";
        echo "准备进入循环";
        // ID自增
        $count = 0;
        $customKey = [];
        $systemKey = [];
        $law_case_batch_number = 0;
        while(true){
            try {
                $clientModel = new MeClientModel();
                app()->gcHelper->gfGetRedis()->list("zlh_test")->for_each(function ($v,$list_length) use (&$customKey,&$systemKey,&$resData,$clientModel,$url,&$count,&$law_case_batch_number) {
                    echo "进入队列\n";
                    // 取出数据转化为数组
                    $vArr = json_decode($v,true);
                    $fmtEx = json_decode($vArr['Extra_parameter'],true);
                    $fileId = $fmtEx['file_id'];
                    // 遍历并且获取对应的key
                    // 设置导入批次号
                    if(isset($vArr['Is_header']) && $vArr['Is_header']){
                        // 如果是header需要清空一次
                        $customKey = [];
                        $systemKey = [];
                        $h_client_id = $fmtEx['client_id'];
                        $clientInfo =  $clientModel->getByIdNoAuth($h_client_id,['client_import_count','client_code','client_custom_json','client_map_excel_file_column_header_to_database_table_field']);
                        $systemArr = $clientInfo['client_map_excel_file_column_header_to_database_table_field'] ? json_decode($clientInfo['client_map_excel_file_column_header_to_database_table_field'],true)['map_excel_file_column_header_to_database_table_field'] : [];
                        $customArr = $clientInfo['client_map_excel_file_column_header_to_database_table_field'] ? json_decode($clientInfo['client_map_excel_file_column_header_to_database_table_field'],true)['map_excel_file_column_header_to_database_table_field_custom'] : [];
                        $excelData = $vArr['Value'];
                        // 设置委托方编号为当前委托方最大导入批次+1
                        $client_import_count =  (int)$clientInfo['client_import_count'];
                        $law_case_batch_number = $client_import_count + 1;
                        // 更新当前委托方最大导入批次
                        $clientModel
                            ->withoutGlobalScopes()
                            ->where('client_id',$h_client_id)
                            ->update([
                            'client_import_count' => $law_case_batch_number
                        ]);
                        // trim字符串 处理隐射字段
                        foreach($excelData as $vKey => $vValue){
                            $excelData[$vKey] = str_replace(["\"","\n","\t","\r"],["","","",""],$vValue);
                        }
                        foreach($customArr as $cKey => $cValue){
                            foreach($excelData as $excelKey => $excelValue){
                                if($excelValue == $cValue['title']){
                                    $customKey[$excelKey] = $cValue['key'];
                                    // 剔除数据降低数组长度
                                    unset($excelData[$excelKey]);
                                }
                            }
                        }
                        foreach($systemArr as $sKey => $sValue){
                            foreach($excelData as $excelKey => $excelValue){
                                if($excelValue == $sValue['title']){
                                    $systemKey[$excelKey] = $sValue['field'];
                                }
                            }
                        }
                        return false;
                    }else{
                        $vData = $vArr['Value'];
                        foreach($vData as $vKey => $vValue){
                            $vData[$vKey] = str_replace(["\"","\n","\t","\r"],["","","",""],$vValue);
                            $pattern = "/(\d{4})[年\/](\d{2})[月\/](\d{2})日/";
                            // 判断字符串中是否存在日期格式
                            if(preg_match($pattern, $vData[$vKey])) {
                                $result = preg_replace($pattern, "$1-$2-$3", $vData[$vKey]);
                                $vData[$vKey] = $result;
                            }
                        }
                        // 保存需要请求的Req
                        $customReq = [];
                        $systemReq = [];

                        foreach($vData as $vDataKey => $vDataValue){
                            if(isset($customKey[$vDataKey])){
                                $customReq[$customKey[$vDataKey]] = $vDataValue;
                            }
                            if(isset($systemKey[$vDataKey])){
                                $systemReq[$systemKey[$vDataKey]] = $vDataValue;
                            }
                        }
                        $defaultReq = [
                            'client_id' => $fmtEx['client_id'],
                            'law_case_code' => MeLawCaseFunc::getLawCaseUnionCode($fmtEx['client_id'],$count),
                            'owner_id' => $fmtEx['owner_id'],
                            'law_case_custom' => json_encode($customReq,256),
                            // 默认案件的导入主体为自然人
                            'respondent_main_body' => 1,
                            // 默认案件的导入类型为1  经济纠纷
                            'law_case_type_id' => 1,
                        ];
                        $sqlReq = array_merge($defaultReq,$systemReq);
                        // 实例化类
                        static $flag = true;
                        static $meModel = "";
                        static $mePhone = "";
                        if($flag){
                            $meModel = new MeLawCase();
                            $mePhone = new MeLawCasePhoneModel();
                            $flag = false;
                        }

                        // 防止类型错误
                        if(isset($sqlReq['loans_output_money'])&&$sqlReq['loans_output_money']==''){
                            $sqlReq['loans_output_money'] = 0;
                        }
                        if(isset($sqlReq['loans_input_money'])&&$sqlReq['loans_input_money']==''){
                            $sqlReq['loans_input_money'] = 0;
                        }
                        if(isset($sqlReq['loans_periods_should_money'])&&$sqlReq['loans_periods_should_money']==''){
                            $sqlReq['loans_periods_should_money'] = 0;
                        }
                        if(isset($sqlReq['loans_periods_should_money'])&&$sqlReq['loans_periods_should_money']==''){
                            $sqlReq['loans_periods_should_money'] = 0;
                        }


                        if(isset($sqlReq['respondent_phone_ids'])){
                            // 多个号码处理
                            $phoneArr = explode(",",$sqlReq['respondent_phone_ids']);
                            $phone_ids_str = "";
                            $firstPhoneId = 0;
                            foreach($phoneArr as $value){
                                // 校验手机号是否存在 如果已经存在则不进行添加
                                $phoneInfo = $mePhone->getDataByPhone($value);
                                if(!$phoneInfo){
                                    // 加入号码表
                                    $phoneId = $mePhone->add([
                                        'phone_number' => $value,
                                        'phone_status' => 1,
                                        'is_law_case_main_phone' => 1,
                                        'status' => 1,
                                    ]);
                                    $phone_ids_str .= $phoneId.",";
                                    if($firstPhoneId==0){
                                        $firstPhoneId = $phoneId;
                                    }
                                }else{
                                    $phone_ids_str .= $phoneInfo['law_case_phone_id'].",";
                                    if($firstPhoneId==0){
                                        $firstPhoneId = $phoneInfo['law_case_phone_id'];
                                    }
                                }
                                $sqlReq['respondent_phone_ids'] = $phone_ids_str;
                                $sqlReq['main_respondent_phone_id'] = $firstPhoneId;
                            }
                        }
                        $count++;
                        $sqlReq['law_case_batch_number'] = $law_case_batch_number;
                        foreach($sqlReq as $key => $value){
                            if(!$value){
                                unset($sqlReq[$key]);
                            }
                        }
                        echo json_encode($sqlReq,256);
                        $id = $meModel->add($sqlReq,true);
                        echo "结束数据导入 导入数据ID为".$id."\n";
                        echo $url;
                        $res = CurlFunc::CurlGet($url,1,[
                            'fileId' => $fileId,
                            'proceed' => $vArr['Progress']
                        ]);
                         echo $res;
                        echo "发送消息$fileId:".$vArr['Progress']."\n";
                    }
                });
                // 没有队列自动休息一秒
                sleep(1);
            }catch (\Exception $exception){
                // 存在异常
                var_dump($exception);
                echo "\n【error:".$exception->getMessage()."line:".$exception->getLine()."】\n";
            }
        }
        return 0;
    }
}
